// packageA/pages/goodsStorage/goodsStorage.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //搜索词
    searchValue:'',
    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,
    //选择框搜索
    valueSearch: '',
    //筛选条件
    screen: {
      storageId: null,
      storageName: '选择仓库',
      classifyId: null,
      classifyName: '选择品类',
      factoryId: null,
      factoryName: '选择厂家'
    },
    //修改库存数量
    showNum: false,
    storageNum: null,
    //设置库存预警
    showWarning: false,
    warningNum: null,
    //当前登录用户
    user: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      user: app.globalData.userInfo
    })

    //获取列表数据
    this.getList();
  },

  //获取列表数据
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let dataObj={
      selectFields: ['id','goods','storage','num','numberOfWarnings','factory'],
      sort: {
        id: -1
      },
      page: {
        page: this.data.page,
        pageSize: 10
      }
    }

    let screen=this.data.screen;

    //名称模糊查询
    if(this.data.searchValue){
      dataObj['goods.name'] = '%' +this.data.searchValue+ '%';
    }

    //仓库
    if(screen.storageId){
      dataObj['storage.id'] = screen.storageId;
    }

    //品类
    if(screen.classifyId){
      dataObj['goods.classify.id'] = screen.classifyId;
    }

    //厂家
    if(screen.factoryId){
      dataObj['goods.factory.id'] = screen.factoryId;
    }

    let param = {
      isAuth: true,
      className: 'clientRequisition',
      data: dataObj
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;
        console.log('库存列表');
        console.log(result);  

        this.setData({
          list: this.data.list.concat(result)
        })
        Toast.clear();
      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          this.setData({
            showNothing: true
          })
          Toast.clear();
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
      Toast.clear();
    })
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail.value
    })
  },

  //点击搜索
  onSearch(){
    this.refreshListAndPage();
  },

  //删除
  onDelete({currentTarget}){
    Dialog.confirm({
      title: '删除后，将无法恢复, 是否继续?',
      confirmButtonText:'确定',
      cancelButtonText:'不删除了'
    }).then(() => {
      let detail=currentTarget.dataset.detail;

      let param={
        className:"clientRequisition",
        data:{
          id:detail.id
        }
      }

      CommonService.goDelete(param).then(res=>{
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('已删除');
          setTimeout(() => {
            //刷新列表和页码
            this.refreshListAndPage();
          }, 1000);
        }else{
          Toast.fail('操作失败');
        }
      }).catch((error) => {
        Toast.fail('操作失败');
      })

    }).catch(() => {
    });
  },

  //显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })

    let dataset=e.currentTarget.dataset;
    let field=dataset.field;

    this.setData({
      showSelect: true,
      selectField: field
    })

    //仓库
    if(field=='storage'){
      this.setData({
        selectTitle: '仓库',
        showSelectSearch: true
      })
      this.getStorageList();
    }

    //品类
    if(field=='classify'){
      this.setData({
        selectTitle: '品类',
        showSelectSearch: true
      })
      this.getClassifyList();
    }

    //厂家
    if(field=='factory'){
      this.setData({
        selectTitle: '厂家',
        showSelectSearch: true
      })
      this.getFactoryList();
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: '',
      disabled: false
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //仓库
    if(selectField=='storage'){
      id='screen.storageId';
      name='screen.storageName';
    }

    //品类
    if(selectField=='classify'){
      id='screen.classifyId';
      name='screen.classifyName';
    }

    //厂家
    if(selectField=='factory'){
      id='screen.factoryId';
      name='screen.factoryName';
    }

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }

    this.onCloseSelect();
    this.refreshListAndPage();  
  },

  //清除选项
  onCancelSelect(){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;
    let str='';

    //仓库
    if(selectField=='storage'){
      id='screen.storageId';
      name='screen.storageName';
      str='仓库';
    }

    //品类
    if(selectField=='classify'){
      id='screen.classifyId';
      name='screen.classifyName';
      str='品类';
    }

    //厂家
    if(selectField=='factory'){
      id='screen.factoryId';
      name='screen.factoryName';
      str='厂家';
    }

    if(id && name){
      this.setData({
        [id]: null,
        [name]: '选择'+ str
      })
    }

    if(obj){
      this.setData({
        [obj]:null
      })
    }

    this.onCloseSelect();
    this.refreshListAndPage();    
  },

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;

    this.setData({
      valueSearch: e.detail
    })

    //仓库
    if(selectField=='storage'){
      this.getStorageList();
    }

    //品类
    if(selectField=='classify'){
      this.getClassifyList();
    }

    //厂家
    if(selectField=='factory'){
      this.getFactoryList();
    }
  },

  //查询仓库
  getStorageList(){
    let param = {
      isAuth: true,
      className: 'clientStorage',
      data: {
        searchAll: true,
        selectFields: ['id','name']
      }
    }

    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.name,
            id: item.id
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //查询品类
  getClassifyList(){
    let user=app.globalData.userInfo;
    let param = {
      isAuth: false,
      className: 'clientClassify',
      data: {
        searchAll: true,
        selectFields: ['id','name','subsidiaryOrgan'],
        'subsidiaryOrgan.id': user.departObj[0].companyId
      }
    }

    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.name,
            id: item.id
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //查询厂家
  getFactoryList(){
    let user=app.globalData.userInfo;
    let param = {
      isAuth: false,
      className: 'clientSupplierFactories',
      data: {
        searchAll: true,
        selectFields: ['id','name','subsidiaryOrgan'],
        'subsidiaryOrgan.id': user.departObj[0].companyId
      }
    }

    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.name,
            id: item.id
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //跳转详情
  goToDetail({currentTarget}){
    let detail=currentTarget.dataset.detail;

    let obj={
      id: detail.id
    }

    wx.navigateTo({
      url: "/packageA/pages/goodsStorageDetail/goodsStorageDetail?paramObj="+JSON.stringify(obj)
    })
  },  

  //显示修改库存数量
  onShowNum(e){
    let detail=e.currentTarget.dataset.detail;
    this.setData({
      showNum: true,
      storageNum: detail.num,
      currentId: detail.id
    })
  },

  //隐藏修改库存数量
  onCloseNum(){
    this.setData({
      showNum: false
    })
  },

  //库存数量
  onChangeNum(e){
    this.setData({
      storageNum: e.detail
    })
  },

  //确认修改库存数量
  onConfirmNum(){
    let param={
      className:'clientRequisition',
      data:{
        id: this.data.currentId,
        num: this.data.storageNum
      }
    }

    CommonService.goSave(param).then(res=>{
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('设置成功');

        this.onCloseNum();
        
        setTimeout(() => {
          this.refreshListAndPage();
        }, 1000);
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  //显示库存预警
  onShowWarning(e){
    let detail=e.currentTarget.dataset.detail;
    this.setData({
      showWarning: true,
      warningNum: detail.numberOfWarnings,
      currentId: detail.id
    })
  },

  //隐藏库存预警
  onCloseWarning(){
    this.setData({
      showWarning: false
    })
  },

  //库存预警
  onChangeWarning(e){
    this.setData({
      warningNum: e.detail
    })
  },

  //确认库存预警
  onConfirmWarning(){
    let param={
      className:'clientRequisition',
      data:{
        id: this.data.currentId,
        numberOfWarnings: this.data.warningNum
      }
    }

    CommonService.goSave(param).then(res=>{
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('设置成功');

        this.onCloseWarning();
        
        setTimeout(() => {
          this.refreshListAndPage();
        }, 1000);
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})